package cn.jbit.stream.gson;

import cn.jbit.stream.pojo.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.List;

/**
 * @author 张在成
 */
public class TestGson {

    /**
     * 大多数用GsonBuilder进行json的序列化与反序列化
     */
    @Test
    public  void  gsonTest(){

        User user=new User();
        user.setId(1);
        user.setName("zaicheng");
        user.setPassword("123.com");
        user.setDate(new Date());

        Gson gson=new GsonBuilder().serializeNulls().setPrettyPrinting().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String s = gson.toJson(user);
        System.out.println(user);
        System.out.println(s);

        User user1 = gson.fromJson(s, User.class);

        System.out.println(user1);

    }

    /**
     *  gson的反序列化
     */
    @Test
    public  void  testUnSerialize(){
        String json="{\n" +
                "  \"id\": 1,\n" +
                "  \"name\": \"zaicheng\",\n" +
                "  \"password\": \"123.com\",\n" +
                "  \"date\": \"2021-10-03 16:22:47\"\n" +
                "}";

        Gson gson=new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

        User user = gson.fromJson(json, User.class);
        List<User> users= gson.fromJson(json, new TypeToken<List<User>>() {
        }.getType());
        System.out.println(users);

    }



}
